import Cookies from 'js-cookie'
import { forEach, hasKey } from './tools'

export const setTitle = (title) => {
  window.document.title = title || 'Advanced'
}

export const setToken = (token, tokenName = 'token') => {
  Cookies.set(tokenName, token)
}

export const getToken = (tokenName = 'token') => {
  return Cookies.get(tokenName)
}

/**
 * @param {Array} list 通过路由列表得到菜单列表
 * @returns {Array}
 */
export const getMenuByRouter = (list) => {
  let res = []
  forEach(list, item => {
    if (!item.meta || (item.meta && !item.meta.hideInMenu)) {
      let obj = {
        icon: (item.meta && item.meta.icon) || '',
        name: (item.meta && item.meta.name) || '',
        path: item.name,
        meta: item.meta
      }
      if (hasChild(item)) {
        obj.children = getMenuByRouter(item.children)
      }
      if (item.meta && item.meta.href) obj.href = item.meta.href
      res.push(obj)
    }
  })
  return res
}

export const hasChild = (item) => {
  return item.children && item.children.length !== 0
}

const showTitle = (item, vm) => {
  console.log('showTitle', item.meta)
  console.log('showTitle', item.meta.name || item.name)
  return (item.meta && item.meta.name) || item.name
}
